<?php

class ViewMonitoringController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
//			array('allow',  // allow all users to perform 'index' and 'view' actions
//				'actions'=>array('index','view'),
//				'users'=>array('*'),
//			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','update','view'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','index','view','export','cekexport'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
       
        public static function parseDateRange($value)
        {
            if (preg_match("@(\d{2}\/\d{2}\/\d{4})\s*-\s*(\d{2}\/\d{2}\/\d{4})@", $value, $match)) {
                return array($match[1], $match[2]);
            }
            return false;
        }
        
        public function actionExport()
        {
            
            $model=new ViewMonitoring;
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['ViewMonitoring']))
		{
                    $model->attributes = $_POST['ViewMonitoring'];
                    $exportTo = $model->exportTo;
                    $statusMobil = $model->statusMobil;
                    
                    if($model->validate())
                    {
                        $date= self::parseDateRange($model->created);
                        $startDate= date("Y-m-d", strtotime($date[0]));
                        $endDate= date("Y-m-d", strtotime($date[1]));
                        $c = new CDbCriteria;
                        $c->condition = 'created BETWEEN "'.$startDate.'" AND "'.$endDate.'"';
                        if(!empty($statusMobil))
                        {
                            $c->addCondition('statusMobil = :statusMobil', 'AND');
                            $c->params = array(':statusMobil' => $statusMobil);
                        }
                        $model = ViewMonitoring::model()->findAll($c);
                        if(empty($model))
                        {
                            $messageType = 'warning';
                            $message = Yii::t('controller', "<strong>Ouch..Sorry!</strong> Data not found or could not be exported.");
                            Yii::app()->user->setFlash($messageType, $message);
                            $this->redirect(array('viewmonitoring/export/'));
//                            Yii::app()->end();
                        }
                        else
                        {
                            $data = array();
                            foreach ($model as $v) {
                                $data[] = array(
                                    'date' => date('d-m-Y', strtotime($v->timbanganMasuk)),
                                    'noTiket' => $v->noTiket,
                                    'noDokumen' => $v->noDokumen,
                                    'noPolisi' => $v->noPolisi,
                                    'deskripsi' => $v->deskripsi,
                                    'statusMobil' => $v->statusMobil,
                                    'gate' => $v->gate,
                                    'timbanganMasuk' => date('H:i:s', strtotime($v->timbanganMasuk)),
                                    'waktuParkir' => date('H:i:s', strtotime($v->waktuParkir)),
                                    'waktuMulai' => date('H:i:s', strtotime($v->waktuMulai)),
                                    'targetWaktu' => date('H:i:s', strtotime($v->targetWaktu)),
                                    'waktuSelesai' => date('H:i:s', strtotime($v->waktuSelesai)),
                                    'timbanganKeluar' => date('H:i:s', strtotime($v->timbanganKeluar)),
                                );
                            } 
                            
                            $r = new YiiReport();
                            $heading = Yii::t('controller', 'Data Monitoring Tanggal '.date('d-m-Y', strtotime($startDate)).' s/d '.date('d-m-Y', strtotime($endDate)));
                            
                            $r->setHeading($heading);
                            
                            if($exportTo == 'excel2007')
                            {
                               $template = 'template_monitoring.xlsx';
                               $r->loadTemplate($template);
                               $config = array(
                                            array(
                                                'id' => 'print',
                                                'data' => array(
                                                    'printDate' => date('d-m-Y H:i', time()),
                                                    'printBy' => Yii::app()->user->getState('fullName'),
                                                ),
                                            ),
                                            array(
                                                'id' => 'mt',
                                                'repeat' => true,
                                                'data' => $data,
                                                'minRows' => 0,
                                            ),
                                   );
                                $r->load($config);
                                echo $r->render($exportTo, 'Monitoring');
                            }
                            else
                            {
                                $this->generatePDF($data);
                            }
                        }
                    }
		}

		$this->render('export',array(
			'model'=>$model,
		));
            
        }

        private function generateTable($param) {
            $html = '<span>Tanggal Cetak : '.date('d-m-Y H:i', time()).'</span><br/>';
            $html .= '<span>Dicetak Oleh  : '.Yii::app()->user->getState('fullName').'</span>';
            $html .= '
                    <table class="table table-striped table-bordered table-condensed">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th>No Tiket</th>
                                <th>No Dokumen</th>
                                <th>No Polisi</th>
                                <th>Kendaraan</th>
                                <th>Status</th>
                                <th>Gate</th>
                                <th>Masuk Timbangan</th>
                                <th>Masuk Parkir</th>
                                <th>Mulai</th>
                                <th>Target</th>
                                <th>Selesai</th>
                                <th>Keluar Timbangan</th>
                            </tr>
                        </thead>
                        <tbody>';
                        $i = 1;
                        foreach ($param as $v) {
                            $class = ($i % 2 == 1) ? 'odd' : 'even';
                            $html .= '
                                <tr class="'.$class.'">
                                    <td>'.$v['date'].'</td>
                                    <td>'.$v['noTiket'].'</td>
                                    <td>'.$v['noDokumen'].'</td>
                                    <td>'.$v['noPolisi'].'</td>
                                    <td>'.$v['deskripsi'].'</td>
                                    <td>'.$v['statusMobil'].'</td>
                                    <td>'.$v['gate'].'</td>
                                    <td>'.$v['timbanganMasuk'].'</td>
                                    <td>'.$v['waktuParkir'].'</td>
                                    <td>'.$v['waktuMulai'].'</td>
                                    <td>'.$v['targetWaktu'].'</td>
                                    <td>'.$v['waktuSelesai'].'</td>
                                    <td>'.$v['timbanganKeluar'].'</td>
                                </tr>';
                            $i++;
                        }
            $html .= '</tbody></table>';
            return $html;
        }
        
        public function generatePDF($param) {
            $html = $this->generateTable($param);
            Yii::import('application.vendors.mpdf.*');
            $mpdf=new mPDF('c','A4','','',10,10,15,10,'','','L'); 
            $mpdf->SetCreator('Abah');
            $mpdf->SetDisplayMode('fullpage');

            $mpdf->list_indent_first_level = 0;	// 1 or 0 - whether to indent the first level of a list

            // LOAD a stylesheet
            $path = Yii::getPathOfAlias('webroot');
            $stylesheet = file_get_contents($path.'/themes/theme/css/gridpdf.css');
            $mpdf->WriteHTML($stylesheet,1);	// The parameter 1 tells that this is css/style only and no body/html/text

            $mpdf->WriteHTML($html,2);

            $mpdf->Output('Monitoring.pdf','I');
            exit;
        }


        private function setFormat($time)
        {
            if(isset($time))
            {
                $format = array();
                if($time->h !== 0)
                {
                    $format[] = '%h jam';
                }
                if($time->i !== 0)
                {
                    $format[] = '%i menit';
                }
                if($time->s !== 0)
                {
                    $format[] = '%s detik';
                }
                    if(count($format) > 1) {
                        $format = array_shift($format).' '.array_shift($format).' '.array_shift($format);
                    } else {
                        $format = array_pop($format);
                    } 
                    return $format;
            }
        }
        
        public function getInterval($start,$end)
        {
            if(isset($start,$end))
            {
                $startTime = new DateTime($start);
                $endTime = new DateTime($end);
                $interval = $endTime->diff($startTime);
                $format = $this->setFormat($interval);
                $timeInterval = $interval->format($format);
                return $timeInterval;
            }
        }
        
        public function getStatus($data){
                $model = $this->loadModel($data->id);
                $standar = explode(':', $model->standarWaktu);
                //Set format waktuSelesai
                $dn = new DateTime($model->waktuSelesai);
                $endTime = $dn->format('H:i:s');
                //Target
                $target = new DateTime($model->targetWaktu);
                $timeTarget = $target->format('H:i:s');
                
                if($endTime <= $timeTarget)
                    $element = '<span class="label label-success"><i class="fa fa-check-square-o"></i></span>';
                else
                    $element = '<span class="label label-important"><i class="fa fa-dot-circle-o"></i></span>';
                
                return $element;
        }

         /**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
        public function actionView($id)
	{
		$model = $this->loadModel($id);
                $standar = explode(':', $model->standarWaktu);
                //Set format waktuSelesai
                $dn = new DateTime($model->waktuSelesai);
                $endTime = $dn->format('H:i:s');
                //Target
                $target = new DateTime($model->targetWaktu);
                $timeTarget = $target->format('H:i:s');
                //Set Interval
                $start = new DateTime($timeTarget);
                $end = new DateTime($endTime);
                $interval = $end->diff($start);
                $format = $this->setFormat($interval);
                
                if($endTime <= $timeTarget)
                    $result = '<span class="label label-success"> Sisa waktu dari target '.$timeTarget.': '.$interval->format($format).'</span>';
                else
                    $result = '<span class="label label-important"> Waktu keluar gudang melebihi target ('.$timeTarget.') : '.$interval->format($format).'</span>';
                  		
                $model = $this->loadModel($id);
                $ekspedisi = '';
                $rute = '';
                if($model->statusMobil === 'Muat')
                {
                    $ekspedisi = Ekspedisi::model()->findByAttributes(array('tb_bongkar_muat_id' => $model->tb_bongkar_muat_id));
                    if(empty ($ekspedisi))
                        throw new CHttpException(404,'Data Ekspedisi is empty.');
                    $rute = Rute::model()->findByPk(array('id' => $ekspedisi->ref_rute_id));
                }
                //Get Interval timbanganMasuk - waktuParkir
                $timbanganParkir = $this->getInterval($model->timbanganMasuk,$model->waktuParkir);
                //Get Interval waktuParkir - waktuMulai
                $parkirGudang = $this->getInterval($model->waktuParkir, $model->waktuMulai);
                
                
                $this->render('view',array(
			'model'=>$model,
                        'ekspedisi'=>$ekspedisi,
                        'rute'=>$rute,
                        'result'=>$result,
                        'timbanganParkir'=>$timbanganParkir,
                        'parkirGudang'=>$parkirGudang,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new ViewMonitoring('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ViewMonitoring']))
			$model->attributes=$_GET['ViewMonitoring'];

		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new ViewMonitoring('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ViewMonitoring']))
			$model->attributes=$_GET['ViewMonitoring'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=ViewMonitoring::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='view-monitoring-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
 
}
